package com.zpb.framework.job;

import com.zpb.framework.domain.entity.Article;
import com.zpb.framework.mapper.ArticleMapper;
import com.zpb.framework.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2025/9/17
 */
@Component
public class upateViewCountJob {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleMapper articleMapper;

    @Scheduled(cron = "0/10 * * * * *")
    public void upateViewCount() {
        Set<Long> updatedIdSet = redisCache.getCacheSet("article:viewCount:updated");
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");

        if (viewCountMap == null) {
            return;
        }
        Set<Map.Entry<String, Integer>> viewCountEntrySet = viewCountMap.entrySet();
        viewCountEntrySet.stream()
                .filter(entry -> updatedIdSet.contains(entry.getKey()))
                .forEach(entry -> {
                    articleMapper.updateById(new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()));
                });
        redisCache.deleteObject("article:viewCount:updated");
    }
}
